#!/bin/bash
## Author wen
## UPDATE 2023-01-20

export JAVA_HOME=/usr/local/jdk-17

PROJECT_PATH=/opt/deploye-jar/dev/novel-cloud/$1
JAVA_FILE=$1
BOOT_ENV="-Dspring.profiles.active=dev"
JVM_OPTS="-XX:MetaspaceSize=100m -XX:MaxMetaspaceSize=300m -XX:+UseZGC -Xms512m -Xmx512m -Xss256k"
JVM_DUMP="-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=${PROJECT_PATH}/heapdump.hprof"
JAVA_AGENT=""
#JAVA_AGENT="-javaagent:/opt/apache-skywalking-apm-bin/agent/skywalking-agent.jar -Dskywalking.agent.service_name=orange-rabbit-auth -Dskywalking.collector.backend_service=172.24.38.168:11800"
JAVA_DEBUG=""
JAVA_DEBUG="-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:50052"
JAVA_NACOS=""
#JAVA_NACOS="-DPROJECT_NAMESPACE=${ENV} -DNACOS_SERVER_ADDR=172.29.211.234:80 -DNACOS_NAMESPACE=${ENV} -Dspring.security.user.name=nacos -Dspring.security.user.password=nacos"

version="1.0.1";

appName=${PROJECT_PATH}/${JAVA_FILE}.jar
cmd=restart

#echo "========================= 移除旧的jar ============================"
#rm -rf $appName

echo "========================= 解压新的jar ============================"
# tar zxvf ${PROJECT_PATH}/package.tgz -C ${PROJECT_PATH}

if [ -z $appName ];then
  appName=`ls -t |grep .jar$ |head -n1`
fi

function start()
{
	PID=$(ps -ef | grep ${JAVA_FILE}.jar | grep -v grep | awk '{ print $2 }')
  if [ -z "$PID" ]
    then
  do_start
    else
  echo "Maybe $appName is running, please check it..."
    fi
}

function do_start()
{
  echo "The $appName do starting..."
  #nohup java -jar ${JAVA_AGENT} ${JVM_OPTS} ${JVM_DUMP} ${JAVA_DEBUG} ${JAVA_NACOS} ${BOOT_ENV} ${JAVA_FILE}.jar > /dev/null 2>&1 &
  nohup java -jar -XX:MetaspaceSize=100m -XX:MaxMetaspaceSize=300m -XX:+UseZGC -Xms512m -Xmx512m -Xss256k ${JAVA_FILE}.jar > /dev/null 2>&1 &
  # timeout 15s tail -1f ${PROJECT_PATH}/logs/logFile.log
  sleep 5
  echo "The $appName shell is ok!!!"
}

function stop()
{
	PID=$(ps -ef | grep ${JAVA_FILE}.jar | grep -v grep | awk '{ print $2 }')
	if [ -z "$PID" ]
	then
    echo "The $appName port is closed"
	else
    echo "The $appName do stopping..."
    kill ${PID}
	fi
}

function restart()
{
  stop
  sleep 5
  do_start
}

function backup() 
{
  # get backup version
  backupApp=`ls |grep -wv $releaseApp$ |grep .jar$`

  # create backup dir
  if [ ! -d "backup" ];then
    mkdir backup
  fi

  # backup
  for i in ${backupApp[@]}
  do
    echo "backup" $i
    mv $i backup
  done
}

function status()
{
	PID=$(ps -ef | grep ${JAVA_FILE}.jar | grep -v grep | awk '{ print $2 }')
      if [ -z "$PID" ]
	then
	    echo "The $appName port is closed"
	else
	    echo "The $appName port is running" 
	fi
}


function usage()
{
  echo "Usage: $0 {start|stop|restart|status|stop -f}"
  echo "Example: $0 start"
  exit 1
}

case $cmd in
	start)
	start;;

	stop)
	stop;;
	
	restart)
	restart;;
	
	status)
	status;;
	
	*)
	usage;;
esac
